#include <iostream>

#include "Interface.h"
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
struct ApiConfig {
  std::string key;
  std::string url;
};

ApiConfig load_api_config(const char* config_path) {
  using namespace rapidjson;

  // 读取文件流
  FILE* fp = fopen(config_path, "rb");
  if (!fp) {
    throw std::runtime_error("Config file not found");
  }

  char readBuffer[65536];
  FileReadStream is(fp, readBuffer, sizeof(readBuffer));

  // 解析JSON
  Document doc;
  doc.ParseStream(is);
  fclose(fp);

  // 错误检查
  if (doc.HasParseError()) {
    throw std::runtime_error("JSON parse error");
  }

  if (!doc.HasMember("api_config") || !doc["api_config"].IsObject()) {
    throw std::runtime_error("Invalid config structure");
  }

  const Value& config = doc["api_config"];
  ApiConfig result;

  // 提取API配置
  if (config.HasMember("APIKEY") && config["APIKEY"].IsString()) {
    result.key = config["APIKEY"].GetString();
  }

  if (config.HasMember("APIURL") && config["APIURL"].IsString()) {
    result.url = config["APIURL"].GetString();
  }

  return result;
}
int main(int argc, char* argv[])  {
  try {
    if (argc < 2) {
      throw std::invalid_argument("Usage: " + std::string(argv[0]) + " <config_file_path>");
    }
    ApiConfig config = load_api_config(argv[1]);
    std::cout << "API Key: " << config.key << "\n"
              << "API URL: " << config.url << std::endl;
    // 初始化接口类
    Interface interface(config.url, config.key);
    // 设置上下文数量
    interface.SetContextSize(100);  // 例如，设置为 100 条历史消息
    // 设置最大tokens
    interface.SetMaxTokensSize(2000);  // 例如，设置为 2000 tokens
    // 启动聊天
    std::string prompt;
    while (true) {
      std::cout << "You: ";
      std::getline(std::cin, prompt);

      if (prompt == "exit") {
        std::cout << "[Interface] Exiting chat..." << std::endl;
        break;
      }  // 如果输入为空，跳过请求
      if (prompt.empty()) {
        std::cout << "[Interface] Input cannot be empty. Please try again."
                  << std::endl;
        continue;
      }
      if (!interface.SetPrompt(prompt)) {
        std::cout << "Input error" << std::endl;
      }
    }
  } catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
  return 0;
}
